import 'dart:async';
import 'dart:convert';
import 'dart:html';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/base/page_constance.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/modle/more/ui/more_moneyjuan_page.dart';
import 'package:shopping_group/modle/play/bloc/zfb_html_bloc.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/widget_utils.dart';

class WxHtmlPage extends StatefulWidget {
  final String openType;
  final String orderId;
  final String orderName;

  WxHtmlPage({Key key, this.openType, this.orderId, this.orderName})
      : super(key: key);

  @override
  _WxHtmlPageState createState() => _WxHtmlPageState();
}

class _WxHtmlPageState extends State<WxHtmlPage> {
  var htmlId;
  StreamSubscription _zfSubscription;
  StreamSubscription _closeSubscription;
  ZfbHtmlBloc _bloc;
  Timer _countdownTimer;
  bool isRunning = false;

  @override
  void initState() {
    super.initState();
    _bloc = ZfbHtmlBloc();
    // htmlId = Utils.getUUid();

    // StringBuffer url = StringBuffer();
    // List<String> gdLists = this.widget.htmlData.split('&');
    // int count = gdLists.length;
    // for (var i = 0; i < count; i++) {
    //   url..write(gdLists[i]);
    //   if (count - 1 != i) {
    //     url..write('&');
    //   }
    // }
    // LogUtil.e(url, tag: 'WxHtml.............../////////////');
    // //ignore: undefined_prefixed_name
    // ui.platformViewRegistry.registerViewFactory(
    //     htmlId,
    //     (int viewId) => IFrameElement()
    //       ..style.border = 'none'
    //       ..height = '800'
    //       ..src = url.toString());
    //   ..srcdoc = """
    // <!DOCTYPE html>
    // <html>
    //   <body>
    //     <script src=>www.baidu.com</script>
    //   </body>
    // </html>
    // """);

    // <script
    // String url = request.getHeader("Referer");
    // System.out.println(url);
    // </script>

    _closeSubscription = eventBus.on<ZfbHtmlCloseEvent>().listen((event) {
      String openType = this.widget.openType;
      String orderId = this.widget.orderId;
      bool isZfOk = 'Y' == event.isZf ? true : false;

      if (!mounted) {
        return;
      }
      if (isZfOk) {
        cancelTimer();
        if (openType == 'ESOT_SHOP') {
          RouteUtil.popUntil(PageConstance.MAIN_PAGE);
          RouteUtil.goView(PageConstance.ALL_ORDER_PAGE);
        } else if ('ESOT_RB' == openType) {
          RouteUtil.popUntil(PageConstance.MAIN_PAGE);
          RouteUtil.goView(PageConstance.MORE_ST_PAGE);
        } else if ('ESOT_JOIN' == openType) {
          //RouteUtil.popUntil(PageConstance.MAIN_PAGE);
          // RouteUtil.goParameter(PingtuanPlayokPage(
          //   entity: this.widget.entity,
          // ));
          // RouteUtil.goParameter(VideoPage(
          //     groupSpecId: this.widget.entity.groupSpecId,
          //     myLastJoinId: orderId,
          //     videoUrl: this.widget.entity.failSeeVideoUrl));
        } else if ('ESOT_MO' == openType) {
          RouteUtil.popUntil(PageConstance.MAIN_PAGE);
          RouteUtil.goParameter(MoreMoneyJuanPage(byYonJin: 'N'));
        } else {
          RouteUtil.closeView();
        }
      }
      isRunning = false;
    });

    _zfSubscription = eventBus.on<ZfbHtmlEvent>().listen((event) {
      String openType = this.widget.openType;
      String orderId = this.widget.orderId;
      bool isZfOk = 'Y' == event.isZf ? true : false;
      if (!isZfOk) {
        if (openType == 'ESOT_SHOP') {
          RouteUtil.popUntil(PageConstance.MAIN_PAGE);
          RouteUtil.goView(PageConstance.DFK_VIEW_PAGE);
        } else {
          BaseConstant.changePageIndex = 4;
          eventBus.fire(ToChangePageEvent());
          RouteUtil.popUntil(PageConstance.MAIN_PAGE);
        }
      } else {
        if (openType == 'ESOT_SHOP') {
          RouteUtil.popUntil(PageConstance.MAIN_PAGE);
          RouteUtil.goView(PageConstance.ALL_ORDER_PAGE);
        } else if ('ESOT_RB' == openType) {
          RouteUtil.popUntil(PageConstance.MAIN_PAGE);
          RouteUtil.goView(PageConstance.MORE_ST_PAGE);
        } else if ('ESOT_JOIN' == openType) {
          //RouteUtil.popUntil(PageConstance.MAIN_PAGE);
          // RouteUtil.goParameter(PingtuanPlayokPage(
          //   entity: this.widget.entity,
          // ));
          // RouteUtil.goParameter(VideoPage(
          //     groupSpecId: this.widget.entity.groupSpecId,
          //     myLastJoinId: orderId,
          //     videoUrl: this.widget.entity.failSeeVideoUrl));
        } else if ('ESOT_MO' == openType) {
          RouteUtil.popUntil(PageConstance.MAIN_PAGE);
          RouteUtil.goParameter(MoreMoneyJuanPage(byYonJin: 'N'));
        } else {
          RouteUtil.closeView();
        }
      }
    });

    // _countdownTimer =
    //     new Timer.periodic(new Duration(microseconds: 500), (timer) {
    //   if (!mounted || isRunning) {
    //     return;
    //   }
    //   isRunning = true;
    //   Map<String, dynamic> data = {};
    //   data['orderType'] = this.widget.openType;
    //   data['orderId'] = this.widget.orderId;
    //   _bloc.restDate.add(data);
    // });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          return;
        },
        child: Scaffold(
            appBar: WidgetUtils.showAppar(context, '微信支付结果页面', onTapClose: () {
              Map<String, dynamic> data = {};
              data['orderType'] = this.widget.openType;
              data['orderId'] = this.widget.orderId;
              _bloc.initDate.add(data);
            }),
            body: Container(
              alignment: Alignment.center,
              decoration: new BoxDecoration(
                color: Colours.title_white,
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  //     WidgetUtils.getTextColorView(
                  //         '请用支付宝扫码支付', Colours.text_2222, Dimens.FONT_SIZE_20,
                  //         fontweight: FontWeight.w600),
                  //     _htmlView(),
                  //     SizedBox(
                  //       height: 8,
                  //     ),
                  WidgetUtils.getTextColorView('${this.widget.orderName}',
                      Colours.text_2222, Dimens.FONT_SIZE_16,
                      fontweight: FontWeight.w500),
                  //     SizedBox(
                  //       height: 4,
                  //     ),
                  //     WidgetUtils.getTextColorView(
                  //         '该二维码仅限本订单使用', Colours.text_2222, Dimens.FONT_SIZE_16,
                  //         fontweight: FontWeight.w500),
                  SizedBox(
                    height: 8,
                  ),
                  GestureDetector(
                      onTap: () {
                        Map<String, dynamic> data = {};
                        data['orderType'] = this.widget.openType;
                        data['orderId'] = this.widget.orderId;
                        _bloc.initDate.add(data);
                      },
                      child: Container(
                        margin:
                            EdgeInsets.symmetric(horizontal: 16, vertical: 32),
                        alignment: Alignment.center,
                        width: 120,
                        height: 42,
                        decoration: BoxDecoration(
                          color: Colours.themeColor,
                          borderRadius: BorderRadius.circular(20),
                          border:
                              Border.all(width: 1, color: Colours.themeColor),
                        ),
                        child: WidgetUtils.getTextColorView(
                          '微信支付关闭',
                          Colours.title_white,
                          Dimens.FONT_SIZE_16,
                        ),
                      )),
                ],
              ),
              //HtmlElementView(viewType: htmlId),
            )));
  }

  Future _loginOut() async {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return showAlertDialog();
        }).then((var result) {
      if (null == result) {
        return;
      }
      if (result is String && 'yes' == result) {
        RouteUtil.closeView();
      }
    });
  }

  Widget showAlertDialog() {
    return AlertDialog(
      title:
          WidgetUtils.getTextColorView('选择', Colors.black, Dimens.FONT_SIZE_18),
      content: WidgetUtils.getTextColorView(
          '确定未支付退出？', Colors.black, Dimens.FONT_SIZE_16),
      actions: <Widget>[
        FlatButton(
          onPressed: () {
            Navigator.of(context).pop('yes');
          },
          child: WidgetUtils.getTextColorView(
              '确定', Colors.black, Dimens.FONT_SIZE_16),
        ),
        FlatButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: WidgetUtils.getTextColorView(
                '取消', Colors.black, Dimens.FONT_SIZE_16))
      ],
    );
  }

  void cancelTimer() {
    if (_countdownTimer != null) {
      _countdownTimer.cancel();
      _countdownTimer = null;
    }
  }

  @override
  void dispose() {
    cancelTimer();
    _closeSubscription?.cancel();
    _zfSubscription?.cancel();
    super.dispose();
  }
}
